/**
 * 
 */
package info.niwota.home.fm;

import info.niwota.home.R;
import x.java.io.File;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author qiangli
 *
 */
public class NewFolderActivity extends BaseFileActivity {

	private EditText inputText;
	private String path;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
		setTheme(android.R.style.Theme_Translucent_NoTitleBar);
		setContentView(R.layout.newfolder);

		init();
	}

	private void init() {
		final TextView pathText = (TextView) findViewById(R.id.newfolder_path);
		inputText = (EditText) findViewById(R.id.newfolder_input);
		
		final Button confirmBtn = (Button) findViewById(R.id.newfolder_confirm);
		final Button cancelBtn = (Button) findViewById(R.id.newfolder_cancel);
		final ImageButton viBtn = (ImageButton) findViewById(R.id.newfolder_voiceinput);
		//
		Uri data = getIntent().getData();
		path = data.getPath();
		pathText.setText(path);
		
		String name = Utils.createName();
		inputText.setText(name);
		//
		confirmBtn.setOnClickListener(this);
		cancelBtn.setOnClickListener(this);
		viBtn.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.newfolder_voiceinput:
			startVoiceInputActivityForResult();
			return;
		case R.id.newfolder_confirm:
			doConfirm();
			break;
		case R.id.newfolder_cancel:
			doCancel();
			break;
		default:
		}
		finish();
	}
	
	@Override
	protected void handleVoiceInputActivityResult(String vi, Intent data) {
		inputText.setText(vi);
	}
	
	private void doCancel() {
		setResult(RESULT_CANCELED);
	}

	private void doConfirm() {
		try {
			String name = inputText.getText().toString();
			name = Utils.sanitize(name);
			File newfile = new File(path, name);
			if (newfile.mkdirs()) {
				Intent data = new Intent();
				data.setData(Uri.parse(newfile.toURI().toString()));
				setResult(RESULT_OK, data);
			} else {
				Toast.makeText(this, "Failed to create. " + newfile,
						Toast.LENGTH_LONG).show();
				setResult(RESULT_CANCELED);
			}
		} catch (Exception e) {
			Toast.makeText(this, e.getMessage(),
					Toast.LENGTH_LONG).show();
			setResult(RESULT_CANCELED);
		}
	}
}
